package cn.wdm.ymcc.mq;

import cn.wdm.ymcc.dto.PayNotifyDto;
import cn.wdm.ymcc.service.ICourseUserLearnService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 支付成功通知给course微服务
 * 支付宝成功异步通知 消费投递在mq中的消息，添加用户的购买记录，给他授权
 * MessageExt 里面是要消费的消息Message PayNotifyDto
 */
@Component
@RocketMQMessageListener(
        consumerGroup="course-notify-consummer",
        topic="asynnotifymsg-topic",
        selectorExpression="asynnotifymsg-tag",
        messageModel= MessageModel.BROADCASTING //默认是集群模式，一个消息只会被一个消费者消费
)
public class PaySuccessNotify2CourseConsummer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseUserLearnService courseUserLearnService;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] bytes = messageExt.getBody();
            //1.非空校验
            if(bytes==null||bytes.length==0){
                return;//为空，直接签收
            }
            String str = new String(bytes, StandardCharsets.UTF_8);
            PayNotifyDto payNotifyDto = JSONObject.parseObject(str, PayNotifyDto.class);
            String extParamStr = payNotifyDto.getExtParams();
            if(StringUtils.isEmpty(extParamStr)){
                return;
            }
            //2.保存购买记录，授权
            courseUserLearnService.paySuccessSaveUserLearn(payNotifyDto);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}
